<template>
  <div class="order-detail-container">
    <div class="main-content">
      <div class="order-info">
        <div class="order-header">
          <div
            class="order-status"
            :style="{
              color:
                orderDetail?.status === 4 || orderDetail?.status === 5
                  ? '#ff4000'
                  : '#52c41a',
            }"
          >
            {{ getStatusText(orderDetail?.status) }}
          </div>
          <div class="order-number">订单编号：{{ orderDetail?.orderNo }}</div>
        </div>
        <div class="loading-placeholder" v-if="loading">加载中...</div>
        <div v-else-if="orderDetail">
          <!-- 进度条 -->
          <div class="progress-section">
            <div class="progress-time-line">
              <div
                v-for="(time, index) in orderTimeline"
                :key="index"
                class="time-point"
              >
                <div class="time">{{ time }}</div>
              </div>
            </div>
            <a-steps
              :current="getCurrentStep(orderDetail.status)"
              class="custom-steps"
            >
              <a-step
                v-for="(step, index) in steps"
                :key="index"
                :title="step"
                :status="getStepStatus(index)"
                :class="{
                  'green-step':
                    orderDetail?.status !== 4 && orderDetail?.status !== 5,
                  'red-step':
                    (orderDetail?.status === 4 || orderDetail?.status === 5) &&
                    index === 4,
                }"
              />
            </a-steps>
          </div>
          <!-- 已取消状态 -->
          <div
            v-if="orderDetail.status === 4 || orderDetail.status === 5"
            style="color: red; font-weight: bold; margin-bottom: 20px"
          ></div>
          <div class="order-details">
            <div class="info-section">
              <div class="section-title">订单信息</div>
              <div class="info-content">
                <div class="address-info">
                  <div>
                    收货地址：{{ orderDetail.address?.provinceName }}
                    {{ orderDetail.address?.cityName }}
                    {{ orderDetail.address?.districtName }}
                    {{ orderDetail.address?.detail }}
                  </div>
                  <div>收货人：{{ orderDetail.address?.consignee }}</div>
                  <div>联系电话：{{ orderDetail.address?.phone }}</div>
                </div>
                <div class="order-actions">
                  <!-- 待付款状态显示付款按钮 -->
                  <a-button
                    v-if="orderDetail?.status === 0"
                    type="primary"
                    class="action-button"
                    @click="handlePayment"
                  >
                    前往付款
                  </a-button>
                  <!-- 待收货状态显示确认收货按钮 -->
                  <a-button
                    v-if="orderDetail?.status === 2"
                    type="primary"
                    class="action-button"
                    @click="handleConfirmReceipt"
                  >
                    确认收货
                  </a-button>
                </div>
              </div>
            </div>
            <p>订单时间：{{ formatDate(orderDetail.createdAt) }}</p>
            <p>总金额：¥{{ orderDetail.totalAmount?.toFixed(2) }}</p>
          </div>
          <div class="product-list">
            <table class="order-table">
              <thead>
                <tr>
                  <th>商品名</th>
                  <th>尺码</th>
                  <th>单价</th>
                  <th>数量</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in orderDetail.orderItems" :key="item.id">
                  <td class="product-name-cell">
                    <div class="product-info">
                      <span class="product-name">{{ item.productName }}</span>
                      <img
                        :src="getImageUrl(item.productImage)"
                        alt="商品图片"
                        class="product-image"
                        @error="handleImageError"
                      />
                    </div>
                  </td>
                  <td class="size-cell">{{ item.size }}</td>
                  <td class="price-cell">
                    ¥{{
                      item?.totalPrice && item?.quantity
                        ? (item.totalPrice / item.quantity).toFixed(2)
                        : "0.00"
                    }}
                  </td>
                  <td class="quantity-cell">{{ item.quantity }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="order-info-header">
          <div class="package-info">
            <span class="package-num">包裹1</span>
            <span class="delivery-company">中通快递</span>
            <span class="tracking-number">运单号:78881249666519</span>
            <span class="delivery-time">2025-02-18 19:11:57</span>
            <span class="delivery-address"
              >您已在佛山三山文锦国际7栋109店完成取件...</span
            >
            <a class="more-link">更多></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getOrderDetailUsingPost,
  confirmReceiveUsingPost,
} from "@/api/orderController";
import type API from "@/api";
import { message } from "ant-design-vue";

const route = useRoute();
const router = useRouter();
const orderId = ref(route.params.id);
const loading = ref(true);
const orderDetail = ref<API.OrderDetailVO>();

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return "";
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    const res = await getOrderDetailUsingPost({ id: Number(orderId.value) });
    if (res.data?.code === 0 && res.data.data) {
      orderDetail.value = res.data.data;
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status?: number) => {
  switch (status) {
    case 0:
      return "待付款";
    case 1:
      return "待发货";
    case 2:
      return "待收货";
    case 3:
      return "已完成";
    case 4:
      return "已取消";
    case 5:
      return "已取消";
    default:
      return "未知状态";
  }
};

// 获取当前步骤
const getCurrentStep = (status?: number) => {
  switch (status) {
    case 0:
      return 0; // 待付款
    case 1:
      return 1; // 待发货
    case 2:
      return 2; // 待收货
    case 3:
      return 3; // 已完成
    case 4:
      return 0; // 已取消，清空进度
    default:
      return 0; // 默认
  }
};

// 处理支付
const handlePayment = () => {
  if (!orderDetail.value?.id) {
    message.error("订单ID无效");
    return;
  }

  // 检查订单状态
  if (orderDetail.value.status !== 0) {
    message.warning("该订单不是待支付状态");
    return;
  }

  // 跳转到支付页面，带上订单ID
  router.push({
    name: "payment", // 使用命名路由
    query: {
      orderId: orderDetail.value.id.toString(),
    },
  });
};

// 处理确认收货
const handleConfirmReceipt = async () => {
  if (!orderDetail.value?.id) {
    message.error("订单ID无效");
    return;
  }

  // 检查订单状态
  if (orderDetail.value.status !== 2) {
    message.warning("该订单不是待收货状态");
    return;
  }

  try {
    const res = await confirmReceiveUsingPost({ id: orderDetail.value.id });
    if (res.data?.code === 0 && res.data.data) {
      message.success("确认收货成功");
      // 重新加载订单详情
      await loadOrderDetail();
    } else {
      message.error(res.data?.message || "确认收货失败");
    }
  } catch (error) {
    console.error("确认收货失败:", error);
    message.error("确认收货失败，请稍后重试");
  }
};

// 步骤文案
const steps = ["待付款", "待发货", "待收货", "已完成", "已取消"];

// 模拟的时间线数据
const orderTimeline = [
  "2025-02-16 01:23:22",
  "2025-02-16 01:23:24",
  "2025-02-16 08:16:58",
  "",
  "",
];

// 获取步骤状态
const getStepStatus = (index: number) => {
  if (!orderDetail.value) return "wait";
  const currentStep = getCurrentStep(orderDetail.value.status);

  if (orderDetail.value.status === 4 || orderDetail.value.status === 5) {
    return index === 4 ? "process" : "wait";
  }

  return index === currentStep
    ? "process"
    : index < currentStep
    ? "finish"
    : "wait";
};

// 修改图片路径处理函数
const getImageUrl = (imageName: string | undefined) => {
  if (!imageName) {
    return "";
  }
  // 清理 URL，移除首尾空格
  const cleanUrl = imageName.trim();
  // 如果已经是完整的URL，直接返回清理后的URL
  if (cleanUrl.startsWith("http://") || cleanUrl.startsWith("https://")) {
    return cleanUrl;
  }
  // 否则返回空字符串
  return "";
};

// 修改图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.style.display = "none";
  console.error("图片加载失败:", img.src);
};

onMounted(() => {
  loadOrderDetail();
});
</script>

<style scoped>
.order-detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.order-info {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.progress-section {
  padding: 30px 0;
  position: relative;
}

.progress-time-line {
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: 100%;
  top: 0;
}

.time-point {
  font-size: 12px;
  color: #999;
}

.custom-steps {
  margin-top: 20px;
}

.info-section {
  background: #f8f8f8;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.info-content {
  display: flex;
  justify-content: space-between;
}

.address-info {
  flex: 1;
  line-height: 24px;
  color: #666;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
}

.order-table th {
  height: 40px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  color: #999;
  font-weight: normal;
  text-align: left;
  padding: 8px 16px;
}

.order-table td {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.product-name-cell {
  max-width: 400px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-name {
  margin-right: 20px;
  color: #333;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.price-cell {
  color: #ff4000;
}

.green-step {
  :deep(.ant-steps-item-title) {
    color: #52c41a !important;
  }
  :deep(.ant-steps-item-icon) {
    background-color: #52c41a !important;
    border-color: #52c41a !important;
  }
  :deep(.ant-steps-item-tail::after) {
    background-color: #52c41a !important;
  }
}

.red-step {
  :deep(.ant-steps-item-title) {
    color: #ff4000 !important;
  }
  :deep(.ant-steps-item-icon) {
    background-color: #ff4000 !important;
    border-color: #ff4000 !important;
  }
  :deep(.ant-steps-item-tail::after) {
    background-color: #ff4000 !important;
  }
}

.order-details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.action-button {
  background-color: #52c41a;
  border-color: #52c41a;
}

.action-button:hover {
  background-color: #73d13d;
  border-color: #73d13d;
}

.order-info-header {
  background: #f0f5ff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.package-info {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #666;
}

.package-num {
  color: #333;
  font-weight: bold;
}

.delivery-company {
  color: #333;
}

.tracking-number {
  color: #666;
}

.delivery-time {
  color: #ff4000;
}

.more-link {
  color: #1890ff;
  cursor: pointer;
}

.status-cell {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.countdown {
  color: #ff4000;
  font-weight: bold;
}

.status-text {
  color: #666;
}
</style>
